package com.milorad.ads.pages;

import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.spring.injection.annot.SpringBean;

import com.milorad.ads.data.dao.interfaces.AdvertDao;
import com.milorad.ads.data.domain.Advert;
import com.milorad.ads.data.domain.Advert.AdvertStatus;
import com.milorad.ads.pages.admin.LoginPage;


public class AdvertsOverviewPage extends AdvertsFilterPage {

	private static final long serialVersionUID = 1L;
	
	@SpringBean
	private AdvertDao advertDao;
	
	public AdvertsOverviewPage() {				
		
		addLinks();
       	
		Advert advert = new Advert();
		advert.setStatus(AdvertStatus.APPROVED);
		List<Advert> adverts = advertDao.find(advert);
		
		addAdvertsList(adverts);		
	}
	
	public AdvertsOverviewPage(List<Advert> adverts) {
			       
    	addLinks();

       	addAdvertsList(adverts);		
	}
	
	private void addLinks() {
		
		add(new BookmarkablePageLink<Void> ("loginPage", LoginPage.class));
		add(new BookmarkablePageLink<Void> ("createAdLink", CreateAdvertPage.class));
	}

	private void addAdvertsList(List<Advert> filteredAdverts) {		
		
		add(new Label("adsListTitle",  getAdvertsListTitle(filteredAdverts)));
		
		add(new ListView<Advert>("list", filteredAdverts) {
			
			private static final long serialVersionUID = 1L;

			@Override
			protected void populateItem(ListItem<Advert> item) {
				Advert advert = item.getModelObject();
				item.add(new Label("title", advert.getTitle()+" ("+advert.getCategory().getName()+")"));
				
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy");
				String formattedDate = sdf.format(advert.getDate());
				String advertInfo = advert.getCity().getName() + " (" + formattedDate + ")";
				item.add(new Label("info", advertInfo));
				item.add(new Label("text", advert.getText()));				
			}			
		});
	}

	private String getAdvertsListTitle(List<Advert> filteredAdverts) {
		
		String advertsListTitle;
		
		if (filteredAdverts.isEmpty()) {
			advertsListTitle = "No adverts matching the criteria were found.";
		} else if (filteredAdverts.size() > 1){
			advertsListTitle = filteredAdverts.size() + " adverts matching the criteria were found.";
		} else {
			advertsListTitle = filteredAdverts.size() + " advert matching the criteria was found.";
		}
		return advertsListTitle;
	}
}